<script setup>
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { AxiosError } from 'axios';
import authService from "@/services/auth.service";
import personalCenterService from "@/services/personal-center.service";
import { useAuthStore } from '@/stores/auth';
import { showFailToast, showNotify } from 'vant';

const router = useRouter();
const authStore = useAuthStore();

const entity = ref({});
const verifyCodeUrl = ref("");
const formRef = ref();
const rememberMe = ref(true);
const REMEMBER_ME_KEY = "fast_alden_remember_me";
const loading = ref(false);

const rules = reactive({
    username: [
        {
            required: true,
            message: '请输入用户名',
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
        },
    ],
    verifyCode: [
        {
            required: true,
            message: '请输入验证码',
        },
    ],
});

onMounted(async () => {
    updateVerifyCode();

    load();
});

const updateVerifyCode = async () => {
    const res = await authService.getVerifyCode();
    verifyCodeUrl.value = `${res.data.data?.image}`;
    entity.value.verifyCodeKey = res.data.data?.key;
}

const load = async () => {
    const tmp = localStorage.getItem(REMEMBER_ME_KEY);
    if (tmp) {
        const e = JSON.parse(tmp);
        entity.value.username = e.username;
        entity.value.password = e.password;
    }
}


const login = async () => {
    const formEl = formRef.value;
    loading.value = true;
    if (!formEl) {
        loading.value = false;
        return;
    }
    try {
        await formEl.validate();

        const res = await authService.login(entity.value);
        const authData = res.data.data;
        if (authData && authData.token) {
            const { token } = authData;
            authStore.authenticate({ token });

            const userProfile = await personalCenterService.retrieve();
            authStore.setUserProfile(userProfile);

            // warning: 此方式直接将用户名密码明文存入localStorage，并不安全
            // todo：寻找更合理方式实现“记住我”
            if (rememberMe.value) {
                localStorage.setItem(REMEMBER_ME_KEY, JSON.stringify({
                    username: entity.value.username,
                    password: entity.value.password,
                }));
            } else {
                localStorage.removeItem(REMEMBER_ME_KEY);
            }

            showNotify({ message: "登录成功", type: "success" });
            router.push("/home");
        }

    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            showFailToast(msg);
        }
        updateVerifyCode();
        throw err;
    } finally {
        loading.value = false;
    }
};

const forgetPassword = () => {
    router.push({
        path: "/forget-password",
        query: {
            username: entity.username,
        }
    });
}

const register = () => {
    router.push("/register");
}
</script>

<template>
    <div class="h-full w-full top-0 left-0 absolute flex flex-col justify-center login-form-container">
        <VanForm ref="formRef" class="login-form" validate-trigger="onBlur">
            <div class="w-full flex flex-row justify-center login-form-logo-container">
                <img class="login-form-logo" src="@/assets/logo.svg" />
            </div>
            <h3 class="text-center">登录</h3>
            <VanCellGroup inset>
                <VanField v-model:model-value="entity.username" name="username" label="用户名" placeholder="用户名"
                    :rules="rules.username">
                </VanField>
                <VanField v-model:model-value="entity.password" type="password" name="password" label="密码" placeholder="密码"
                    :rules="rules.password">
                </VanField>
                <VanField class="" v-model:model-value="entity.verifyCode" name="verifyCode" label="验证码" placeholder="验证码"
                    :rules="rules.verifyCode">
                    <template #button>
                        <img :src="verifyCodeUrl" class="verify-code" @click="updateVerifyCode()" />
                    </template>
                </VanField>
                <VanCell>
                    <template #title>
                        <VanCheckbox v-model:model-value="rememberMe">记住密码</VanCheckbox>
                    </template>
                    <template #value>
                        <a href="javascript:void(0);" @click="forgetPassword">忘记密码</a>
                    </template>
                </VanCell>
            </VanCellGroup>
            <VanCellGroup inset>
                <VanButton round block type="primary" @click="login">
                    登录
                </VanButton>
                <VanButton class="mt-2" round block @click="register">
                    注册
                </VanButton>
            </VanCellGroup>
        </VanForm>
    </div>
</template>

<style lang="scss" scoped>
.login-form-container {
    .login-form-logo {
        height: 64px;
    }

    .verify-code {
        height: 40px;
    }
}
</style>